package com.ruoyi.framework.provider;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.framework.provider.dto.StableTokenDTO;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WxProvider {

    @Value("${PROGRESS_WECHAT.APPID}")
    private String APPID;

    @Value("${PROGRESS_WECHAT.APPSECRET}")
    private String APPSECRET;


    public String getAccessToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", APPID);
        params.put("secret", APPSECRET);
        params.put("grant_type", "client_credential");
        String result = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/stable_token")
                .body(JSON.toJSONString(params))
                .execute().body();
        if (StringUtils.isNotEmpty(result)) {
            return JSON.parseObject(result, StableTokenDTO.class).getAccess_token();
        }
        return null;
    }

    public String getPhoneNumber(String code) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("code", code);
            String accessToken = getAccessToken();
            String result = HttpRequest.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken)
                    .body(JSON.toJSONString(params))
                    .execute().body();
            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            if (phoneInfo != null) {
                return phoneInfo.getString("phoneNumber");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String authLogin(String code) {
        try {
            String appId = APPID;
            String appSecret = APPSECRET;
            String accessURL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid="
                    + appId + "&secret=" + appSecret + "&js_code=" + code;
            String result1 = HttpRequest.get(accessURL).execute()
                    .body();
            log.info(result1);
            JSONObject jsonObject = JSON.parseObject(result1);
            String openid = jsonObject.getString("openid");
            return openid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
